<?php
// Module Body

function pdns_work(&$data) {
	global $cfg;

	// These have to happen before switching databases
	// so they are selected early.

	// Select hosts
	$query = "SELECT ip, host FROM domains WHERE (id='".$data['id']."' OR owner='".$data['id']."') AND domain = '".$data['domain']."' AND action != 'remove'";
	$dbp = mysql_query($query);

	// Select the old domain name??
	$query="SELECT domain FROM domains WHERE id='".$data['id']."' AND action != 'remove'";
	$oldomain = mysql_query($query);
	$olddom = @mysql_fetch_row($olddomain);
	$data['ip'] = explode('|',$data['ip']);

	// Select PDNS database as defined in config
	if (!@mysql_select_db($cfg['pdns_db'])) {
		webcp_log(1, 0, "pdns.mod.phps", "Failed to select PowerDNS database: ".$cfg['pdns_db'],0 , $echo);
		return;
	} else {
		webcp_log(3, 0, "pdns.mod.phps", "PowerDNS Database selected: ".$cfg['pdns_db'],0 , $echo);
	}
	
	
	// DNS admin email:
	$dns_admin_email = str_replace("@", ".", $cfg['dns_email']);
	if (strrpos($dns_admin_email, ".") != strlen($dns_admin_email)) {
		$dns_admin_email .= ".";
	}
	
	//Create serial number
	$dns_serial = date("Ymd");
	
	// Make it unique
	$SQL = "SELECT MAX(id) as MaxID FROM domains";
	$res = mysql_query($SQL);
	
	if ($id = mysql_fetch_array($res) && mysql_num_rows($res)) {
		$dns_serial .= ($id["MaxID"] + 1);
	} else {
		$dns_serial .= date("His");
	}

	$data['dns_admin_email'] = $dns_admin_email;
	$data['dns_serial'] = $dns_serial;
	$data['old_domain'] = $olddom['domain'];

	switch($data["action"]) {
		case "update":
			pdns_domain_update($data);
			break;
		case "remove":
			pdns_domain_remove($data);
			break;
		case "create":
			pdns_domain_create($data);
			break;
	}
	
	// Log completion
	webcp_log(2, 0, "pdns.mod.phps", "PowerDNS entry for ".$data["domain"]." completed successfully. Type: ".$data['type'].". Action: ".$data['action'],0 , $echo);

	// Select webcp database again
	mysql_select_db($cfg['dbname']);
}

function  pdns_domain_create(&$data) {
	global $cfg;

	switch ($data['type']) {
			case "pointer":
			case "domain":
				// Select old SOA to work with
				$SQL = "SELECT id FROM domains WHERE origin = '".$olddom["domain"]."'";
				$res = mysql_query($SQL);
				if ($id = mysql_fetch_array($res) && mysql_num_rows($res)) {
					// Delete old SOA
					$SQL = "DELETE FROM domains WHERE id = ".$id["id"];
					mysql_query($SQL);
			
					// Delete old RR
					$SQL = "DELETE FROM records WHERE domain_id = ".$id["id"];
					mysql_query($SQL);
				}

				if (strrpos($cfg["dns_server1"], ".") != strlen($cfg["dns_server1"])) {
					$dns_server1 = $cfg["dns_server1"].".";
				} else {
					$dns_server1 = $cfg["dns_server1"];
				}

				// create SOA record
				$SQL = "INSERT INTO domains(name, type) values ('" . $data["domain"] . "', 'NATIVE')";
				mysql_query($SQL);
				$SOAID = mysql_insert_id();
				
				// create SOA record
				$SQL = "INSERT INTO records(domain_id, name, type, content, ttl, prio) values (" . $SOAID . ", '" . $data["domain"] . "', 'SOA', '" . $dns_server1 . " " . $dns_admin_email . " " . $dns_serial . " " . $cfg['dns_refresh'] . " " . $cfg['dns_retry'] . " " . $cfg['dns_expire'] . " " . $cfg['dns_ttl'] . "', '" . $cfg['dns_ttl'] . "', '0')";
				
				mysql_query($SQL);

				// create NS records
				for($i=1; $i<=4; $i++){
					if( !preg_match("/^$|none/", $cfg["dns_server".$i])){
						if (strrpos($cfg["dns_server".$i], ".") != strlen($cfg["dns_server".$i])) {
							$dns_server = $cfg["dns_server".$i].".";
						} else {
							$dns_server = $cfg["dns_server".$i];
						}
						$SQL = "INSERT INTO records (domain_id, name, type, content, ttl) VALUES(";
							$SQL .= $SOAID.",'" . $data["domain"] . "','NS','".$dns_server."',".$cfg["dns_ttl"].")";
						mysql_query($SQL);
					}
				}
		
				// create MX records
				for($i=1; $i<=4; $i++){
					if( !preg_match("/^$|none/", $cfg["mail_exchanger".$i])){
						if (strrpos($cfg["mail_exchanger".$i], ".") != strlen($cfg["mail_exchanger".$i])) {
							$mail_server = $cfg["mail_exchanger".$i].".";
						} else {
							$mail_server = $cfg["mail_exchanger".$i];
						}
						$SQL = "INSERT INTO records(domain_id, name, type, content, ttl, prio) VALUES(";
							$SQL .= $SOAID.",'" . $data["domain"] . "','MX','".$mail_server."',".$cfg["dns_ttl"].", ". ($i * 10) .")";
						mysql_query($SQL);
					}
				}
		
				// create A records for hosts
				while ($ddata = mysql_fetch_array($dbp)) {
					foreach($data['ip'] as $IP) {
						$SQL = "INSERT INTO records(domain_id, name, type, content, ttl) VALUES(";
							$SQL .= $SOAID.",'".$ddata["host"].".".$data['domain']."','A','".$IP."',".$cfg["dns_ttl"].")";
						mysql_query($SQL);
					}
				}

				// create A record for plain domain.ext if requested
				if($data['nohost'] == 'true'){
					foreach($data['ip'] as $IP) {
						$SQL = "INSERT INTO records(zone, name, type, content, ttl) VALUES(";
							$SQL .= $SOAID.",'".$data["domain"]."','A','".$IP."',".$cfg["dns_ttl"].")";
						mysql_query($SQL);
					}
				}
		
				// create A record for hostname aliases
				if (!empty($data['aliases'])) {
				$tmp = explode(" ",$data['aliases']);
					foreach($tmp as $alias){
						foreach($data['ip'] as $IP) {
							$SQL = "INSERT INTO records(domain_id, name, type, content, ttl) VALUES(";
								$SQL .= $SOAID.",'".$alias."','A','".$IP."',".$cfg["dns_ttl"].")";
							mysql_query($SQL);
						}
					}
				}
		
				// create A catchall record if requested
				if ($data['catchall'] == 'true'){
					foreach($data['ip'] as $IP) {
						$SQL = "INSERT INTO records(domain_id, name, type, content, ttl) VALUES(";
							$SQL .= $SOAID.",'*','A','".$IP."',".$cfg["dns_ttl"].")";
						mysql_query($SQL);
					}
				}
				break;

			case "subdomain":
				// Select SOA to use
				$SQL = "SELECT id FROM domains WHERE name = '".$data["domain"]."'";
				$res = mysql_query($SQL);

				if ($id = mysql_fetch_array($res)) {
					// Check if subdomain already exists
					$SQL = "SELECT id FROM records WHERE domain_id = '".$id["id"]."' AND name='".$data["host"]."'";
					$oldsub = mysql_query($SQL);
					if ($osub = mysql_fetch_array($oldsub)) {
						// Delete old subdomain
						$SQL = "DELETE FROM records WHERE id = ".$osub["id"];
						mysql_query($SQL);
					}

					// Create subdomain
					foreach($data['ip'] as $IP) {
						$SQL = "INSERT INTO records(domain_id, name, type, content, ttl) VALUES(";
							$SQL .= $id['id'].",'".$data["host"].".".$data['domain']."','A','".$IP."',".$cfg["dns_ttl"].")";
						mysql_query($SQL);
					}
				}
				break;
		}
}

function pdns_domain_update(&$data) {
	global $cfg;

	pdns_domain_remove($data);
	pdns_domain_create($data);
}

function pdns_domain_remove(&$data) {
	global $cfg, $restartdns;

	// Select old SOA to work with
	$SQL = "SELECT id FROM domains WHERE name = '".$data["domain1"]."'";
	$res = mysql_query($SQL);
	if ($id = mysql_fetch_array($res)) {
		switch ($data['type']) {
			case "pointer":
			case "domain":
				// Delete old SOA
				$SQL = "DELETE FROM domains WHERE id = ".$id["id"];
				mysql_query($SQL);
		
				// Delete old RR
				$SQL = "DELETE FROM records WHERE domain_id = ".$id["id"];
				mysql_query($SQL);
					break;
			case "subdomain":
				// Delete subdomain
				$SQL = "DELETE FROM records WHERE domain_id = ".$id["id"]." AND name='".$data['host'].".".$data['domain']."'";
				mysql_query($SQL);
				break;
		}
	}
}

function pdns_monitor(&$data) {
	global $cfg;
	if (file_exists($cfg['spid']['pdns'])) {
		$pid = intval(trim(file_get_contents($cfg['spid']['pdns'])));
		if (posix_kill($pid,0))
			$data['pdns'] = 'up';
		else {
			$data['pdns'] = 'down';
		}
	} else {
		$data['pdns'] = 'down';
	}
	if ($data['pdns'] == 'down') {
		if ($cfg['service_auto_start'] && $cfg['autostart']['pdns']) {
			webcp_log(2,0,"monitor","service down: pdns - attempting to start",0,$echo);
			bind_start();
			sleep(2);
			if (file_exists($cfg['spid']['pdns'])) {
				$pid = intval(trim(file_get_contents($cfg['spid']['pdns'])));
				if (posix_kill($pid,0))
					$data['pdns'] = 'up';
				else {
					$data['pdns'] = 'down';
				}
			} else {
				$data['pdns'] = 'down';
			}
		}
	}
	if ($data['pdns'] == 'down') {
		webcp_log(1,0,"monitor","service down: pdns",0,$echo);
	}
	return true;
}

function pdns_add_lang(&$data) {
	global $T;
	switch($data['lang']) {
		default:
			$T['named service'] = 'DNS Server';
			break;
	}
}

function pdns_add_cfg(&$cfg) {
	$cfg['spid']['pdns']	= '/var/run/pdns.pid';
	$cfg['init']['pdns']	= '/etc/init.d/pdns';
	$cfg['autostart']['pdns'] = true;
}

function pdns_stop() {
	global $cfg;
	exec($cfg['init']['pdns'].' stop');
}

function pdns_start() {
	global $cfg;
	exec($cfg['init']['pdns'].' start');
}

function pdns_restart() {
	global $cfg;
	exec($cfg['init']['pdns'].' restart');
}
?>
